package com.usian.skill.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.common.CodeMsg;
import com.usian.skill.common.Result;
import com.usian.skill.mq.MqSender;
import com.usian.skill.mq.SkillMsgAge;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.GoodsService;
import com.usian.skill.service.SkillOrderService;
import com.usian.skill.service.SkillService;
import com.usian.skill.vo.GoodsVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/skill")
public class SkillController implements InitializingBean {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SkillOrderService skillOrderService;

    @Autowired
    private SkillService skillService;

    @Autowired
   private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MqSender mqSender;

    private HashMap<Long,Boolean> localoverMap=new HashMap<Long, Boolean>();


    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> goodsVos=goodsService.qclistDB();
        if (!CollectionUtils.isEmpty(goodsVos)){
            for (GoodsVo vo : goodsVos) {
                stringRedisTemplate.opsForValue().set("stockCount"+vo.getId(),vo.getStockCount()+"");

                localoverMap.put(vo.getId(),false);
            }
        }
    }

    @RequestMapping(value="/verifyCode", method=RequestMethod.GET)
    @ResponseBody
    public Result<String> getMiaoshaVerifyCod(HttpServletResponse response, HttpSession session,
                                              @RequestParam("goodsId")long goodsId) {
        String user=(String)session.getAttribute("userId");
        if(user == null) {
            return Result.error(CodeMsg.SESSION_ERROR);
        }
        try {
            BufferedImage image  = skillService.createVerifyCode(user, goodsId);
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "JPEG", out);
            out.flush();
            out.close();
            return null;
        }catch(Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.MIAOSHA_FAIL);
        }
    }




    @RequestMapping("/{path}/skillGood")
    @ResponseBody
    public Result skillGoods(@PathVariable String path, HttpSession session, Long goodsId, Model model){
        String userId=(String) session.getAttribute("userId");
        if (userId==null){
            return  Result.error(CodeMsg.SESSION_ERROR);
        }
        boolean b = skillService.checkPath(userId, goodsId, path);
        if (!b){
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        }
        if (localoverMap.get(goodsId)){
            return Result.error(CodeMsg.MIAO_SHA_OVER);
        }
        //        取出redis库存  并进行判断    如果小于等于0  秒杀失败 无库存
        String stockCount = stringRedisTemplate.opsForValue().get("stockCount" + goodsId);
        if (Integer.parseInt(stockCount)<=0){
            localoverMap.put(goodsId,true);
            return Result.error(CodeMsg.MIAO_SHA_OVER);
        }else {
            stringRedisTemplate.opsForValue().decrement("stockCount"+goodsId);
        }


////        查库存  判断用户选的商品库存是否够 或者大于0  才能进行操作
//        GoodsVo goodsVo=goodsService.getgoodsvobyid(goodsId);
//        if (goodsVo.getStockCount()<=0){
//            model.addAttribute("errmsg","库存不够了");
//            Result.error(CodeMsg.MIAOSHA_FAIL);
//            return "miaosha_fail";
//        }
//        查看当前用户之前是否已经秒杀过该商品了  单个商品只能每人一次
        SkillOrder skillOrder = skillOrderService.getOne(Wrappers.<SkillOrder>lambdaQuery().eq(SkillOrder::getGoodsId, goodsId).eq(SkillOrder::getUserId, userId));
        if (skillOrder!=null){
            stringRedisTemplate.opsForValue().increment("stockCount"+goodsId);
            return Result.error(CodeMsg.REPEATE_MIAOSHA);
        }
        SkillMsgAge skillMsgage=new SkillMsgAge();
        skillMsgage.setGoodsId(goodsId);
        skillMsgage.setUserId(Long.parseLong(userId));
        mqSender.sendSkillMsgage(skillMsgage);


////        如果都没问题  可以执行  删减当前商品的库存数量 以及 生成该商品的订单
//        OrderInfo info=skillService.deleteKuCunAndAddDingDan(userId,goodsVo);
//        model.addAttribute("goods",goodsVo);
//        model.addAttribute("orderInfo",info);
        return Result.success(-1);

    }


    @RequestMapping(value = "/result",method = RequestMethod.GET)
    @ResponseBody
    public Result<Long> miaoshaResult(Model model, HttpSession session,
                                      @RequestParam("goodsId")Long goodsId){
        String userId=(String) session.getAttribute("userId");
        if (userId==null){
            return  Result.error(CodeMsg.SESSION_ERROR);
        }
        long resilt=skillService.getMiaoshaResult(userId,goodsId);
        return Result.success(resilt);

    }

    @RequestMapping(value = "/path",method = RequestMethod.GET)
    @ResponseBody
    public Result<String> getSkillpath(Model model, HttpSession session,
                                      @RequestParam("goodsId")Long goodsId){
        String userId=(String) session.getAttribute("userId");
        if (userId==null){
            return  Result.error(CodeMsg.SESSION_ERROR);
        }
        String miaoshaPath = skillService.createMiaoshaPath(userId, goodsId);
        return Result.success(miaoshaPath);

    }

}
